package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.CartDao;
import dao.GoodsDao;
import dao.OrderDao;
import entity.Cart;
import entity.Comment;
import entity.Goods;
import entity.Order;
import entity.User;
import net.sf.json.JSONArray;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {
	private CartDao cartDao = new CartDao();
	private OrderDao orderDao = new OrderDao();
	private GoodsDao goodsDao = new GoodsDao();
	private Goods goods = new Goods();
	private Cart cart = new Cart();
	DecimalFormat df = new DecimalFormat("######0.00");
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		doPost(req, resp);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");// 这是一个坑，前端传数据进来，要先判断它编码是否正确
		resp.setContentType("text/html;charset=UTF-8");// 防止中文乱码
		
		String act = req.getParameter("act");
		
        // 获取Session中的用户uid
        HttpSession session = req.getSession();
        String ud = (String) session.getAttribute("uid");

//		String ud = req.getParameter("uid");
		req.setAttribute("uid", ud);
		
		int uid = Integer.parseInt(ud);		
		int gid;
		int cartid;
		int shopnum;
		
		String cd;
		String gd;
		
		if (act.equals("0")) { // 访问
			double max_price = 0;
			double total_price = 0;
			int total_num = 0;
			try {
				List<Cart> clist = in(uid);
				req.setAttribute("clist", clist);

				List<Goods> glist = cartDao.querByuIdGoods(uid);
				req.setAttribute("glist", glist);
				
				
				int gg;		
				for(Cart cart: clist) {
					gg = cart.getGid();
					goods.setGid(gg);
					try {
						
						goods = goodsDao.queryById(goods);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}			
					if(goods.getPrice() > max_price) max_price = goods.getPrice();
					total_price = total_price + goods.getPrice() * cart.getShopnum();
					total_num = total_num + cart.getShopnum();
					req.setAttribute("max_price", max_price);
					req.setAttribute("total_price", df.format(total_price));
					req.setAttribute("total_num", total_num);
				}
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(act.equals("1")) { // 添加
			gd = req.getParameter("gid");
			String num = req.getParameter("num");
			gid = Integer.parseInt(gd);		
			shopnum = Integer.parseInt(num);		
			cart = new Cart(uid,gid,shopnum);
			try {
				add(cart,shopnum);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(act.equals("2") ){ // 删除
			cd = req.getParameter("cid");
			cartid = Integer.parseInt(cd);	
			cart.setCartid(cartid);
			try {
				del(cart);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if(act.equals("3") ){ // 修改
			gd = req.getParameter("gid");
			String num = req.getParameter("num");
			gid = Integer.parseInt(gd);	
			shopnum = Integer.parseInt(num);		
			cart = new Cart(uid,gid,shopnum);
			try {
				update(cart);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (!act.equals("0")) { 
			double max_price = 0;
			double total_price = 0;
			int total_num = 0;
			try {
				List<Cart> clist = in(uid);
				req.setAttribute("clist", clist);
				List<Goods> glist = shop(uid);
				req.setAttribute("glist", glist);
				int gg;		
				for(Cart cart: clist) {
					gg = cart.getGid();
					goods.setGid(gg);
					try {
						
						goods = goodsDao.queryById(goods);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}			
					if(goods.getPrice() > max_price) max_price = goods.getPrice();
					total_price = total_price + goods.getPrice() * cart.getShopnum();
					total_num = total_num + cart.getShopnum();					
					
					req.setAttribute("max_price", max_price);
					req.setAttribute("total_price", df.format(total_price));
					req.setAttribute("total_num", total_num);
					
				}
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
		if(!act.equals("0")) {
			Boolean a = true;
			// 把java数组转化成转化成json对象
			JSONArray jsonArray2 = JSONArray.fromObject(a);
			System.out.println(jsonArray2);
			PrintWriter out = resp.getWriter();
			out.print(jsonArray2); // 输出,返给ajax请求
		}else {
			req.getRequestDispatcher("cart.jsp").forward(req, resp);
		}
		

	}

	// 访问购物车 -- 0
	public List<Cart> in(int uid) throws SQLException {
		// 购物车用户记录
		List<Cart> clist = cartDao.querByuIdCart(uid);
		
		return clist;
	}


	// 加入购物车 -- 1
	public void add(Cart cart,int shopnum) throws SQLException {
		if(existsCId(cart)) {
			shopnum = shopnum + cart.getShopnum();
			cart.setShopnum(shopnum);
			System.out.println("已添加过！重新覆盖");
			update(cart);
		}else {
			cartDao.addCart(cart);
			System.out.println("加入购物车成功");
		}
		

	}

	// 删除商品 -- 2
	public void del(Cart cart) throws SQLException {
		cartDao.deleteCart(cart);
		System.out.println("删除成功");
	}

	// 修改商品 -- 3
	public void update(Cart cart) throws SQLException {
		cartDao.updateCart(cart);
		System.out.println("修改成功");
	}
	//获得商品信息
	public List<Goods> shop(int uid) throws SQLException {
		List<Goods> glist = new ArrayList<Goods>();	
		
		glist = cartDao.querByuIdGoods(uid);

		return glist;		
	}
	// 生成订单随机数
	public static String getRandom() {
		String front = "XC";// 前缀
		SimpleDateFormat simpleDateFormat;
		simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String date = simpleDateFormat.format(new Date());
		Random random = new Random();
		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
		// System.out.println(rannum);
		String rand = front + date + rannum;
		System.out.println(rand);
		return rand;
	}

	public boolean existsOId(String oid) throws SQLException {

		if (orderDao.queryByOId(oid) == null) {
			return false;
		}
		return true;
	}
	
	public boolean existsCId(Cart cart) throws SQLException {

		if (cartDao.queryByUGId(cart) == null) {
			return false;
		}
		return true;
	}
	
	
	
}
